<template>
	<div class="user-list-container">
		<el-card class="filter-card">
			<el-form :inline="true" :model="filterForm" class="filter-form">
				<el-form-item label="班级" style="width: 360px">
					<el-select v-model="filterForm.classId" placeholder="请选择班级" clearable>
						<el-option
							v-for="item in classList"
							:key="item.classId"
							:label="getClassDisplayText(item)"
							:value="item.classId"
						>
							{{ getClassDisplayText(item) }}
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleSearch">查询</el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<el-card class="table-card">
			<el-table :data="userList" border style="width: 100%">
				<!-- <el-table-column type="index"> </el-table-column> -->
				<el-table-column label="头像" width="130">
					<template #default="scope">
						<el-image
							:src="scope.row.avatar ? scope.row.avatar : 'Failed'"
							:preview-src-list="[scope.row.avatar ? scope.row.avatar : 'Failed']"
							:initial-index="0"
							fit="cover"
							style="height: 100px; width: 100px"
						></el-image>
					</template>
				</el-table-column>
				<el-table-column prop="typeNumber" label="学号" width="120" sortable />
				<el-table-column prop="uname" label="姓名" width="80"> </el-table-column>
				<el-table-column prop="phoneNumber" label="联系方式" width="120" />
				<el-table-column prop="updateTime" label="更新时间">
					<template #default="scope">
						{{ standardDateTime(scope.row.updateTime) }}
					</template>
				</el-table-column>
				<el-table-column label="查看">
					<template #default="scope">
						<el-button type="info" @click="handleLookInfo(scope.row)">信息</el-button>
						<el-button type="primary" @click="handleLookScore(scope.row)">成绩</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, onActivated } from 'vue'
import { getUserListByClassIdListService, getClassListByUserIdService } from '@/api/user_classname'
import type { TUser } from '@/Types/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
import { getFileSpecificService } from '@/api/file'
import { baseURL } from '@/utils/request'
import { standardDateTime } from '@/Tools/Time/date'

const userStore = useUserStore()
const userId = userStore.userInfo.userInfo.userId
const router = useRouter()

// 筛选表单
const filterForm = ref({
	classId: null as number | null
})

// 班级列表
const classList = ref<
	Array<{
		classId: number
		level: string
		academy: string
		major: string
		grade: string
		classname: number
		createTime: string
		updateTime: string
	}>
>([])

// 用户列表
const userList = ref<TUser[]>([])

// 获取班级列表
const fetchClassList = async () => {
	try {
		const res = await getClassListByUserIdService(userId)
		// 确保数据格式正确
		classList.value = res.data.data.map(
			(item: {
				classId: number
				level: string
				academy: string
				major: string
				grade: number
				classname: number
			}) => ({
				classId: item.classId,
				level: item.level || '',
				academy: item.academy || '',
				major: item.major || '',
				grade: item.grade || 0,
				classname: item.classname || 0
			})
		)
	} catch (error) {
		// console.error('获取班级列表失败:', error)
	}
}

// 获取班级显示文本
const getClassDisplayText = (classInfo: (typeof classList.value)[0]) => {
	if (!classInfo) return ''

	const levelMap: Record<string, string> = {
		undergrad: '本科',
		vocED: '专科'
	}

	const level = levelMap[classInfo.level] || classInfo.level
	const academy = classInfo.academy || ''
	const major = classInfo.major || ''
	const grade = classInfo.grade ? `${classInfo.grade}级` : ''
	const classname = classInfo.classname ? `${classInfo.classname}班` : ''

	return `${level}${academy}${major}${grade}${classname}`.trim()
}

// 获取用户头像
const getUserAvatar = async (avatarId?: number) => {
	if (!avatarId) {
		return null
	}

	try {
		const res = await getFileSpecificService({ id: avatarId, fileType: 'avatar' })
		if (res.data.code === 1 && res.data.data && res.data.data.length > 0) {
			const url = baseURL + '/public/uploads/' + res.data.data[0].fileName
			return url
		}
	} catch (error) {
		// console.error('获取头像失败:', error)
	}

	return null
}

// 获取用户列表
const fetchUserList = async () => {
	if (!filterForm.value.classId) {
		userList.value = []
		return
	}
	try {
		const res = await getUserListByClassIdListService(1, [filterForm.value.classId])
		userList.value = res.data.data

		// 获取所有用户的头像
		for (const user of userList.value) {
			if (user.avatarId) {
				const avatarUrl = await getUserAvatar(user.avatarId)
				if (avatarUrl) {
					user.avatar = avatarUrl
				}
			}
		}
	} catch (error) {
		// console.error('获取用户列表失败:', error)
	}
}

// 保存当前筛选状态到本地存储
const saveFilterState = () => {
	localStorage.setItem(
		'userList_filterState',
		JSON.stringify({
			classId: filterForm.value.classId
		})
	)
}

// 恢复筛选状态
const restoreFilterState = () => {
	try {
		const savedState = localStorage.getItem('userList_filterState')
		if (savedState) {
			const state = JSON.parse(savedState)
			filterForm.value.classId = state.classId
			// 如果有保存的班级ID，则自动查询
			if (filterForm.value.classId) {
				fetchUserList()
			}
		}
	} catch (error) {
		// 恢复失败则忽略
	}
}

// 查询按钮点击事件
const handleSearch = () => {
	fetchUserList()
	saveFilterState()
}

// 获取个人信息
const handleLookInfo = async (row: TUser) => {
	// 保存当前筛选状态
	saveFilterState()
	router.push(`/userInfo/${row.userId}`)
}

// 获取个人成绩
const handleLookScore = async (row: TUser) => {
	// 保存当前筛选状态
	saveFilterState()
	router.push(`/scoreInfo/${row.userId}`)
}

// 组件挂载
onMounted(() => {
	fetchClassList()
	restoreFilterState()
})
</script>

<style scoped>
.user-list-container {
	padding: 20px;
	max-height: 300px;
}

.filter-card {
	margin-bottom: 20px;
}

.filter-form {
	display: flex;
	align-items: center;
}

.table-card {
	margin-top: 20px;
}

.user-name-link {
	color: #409eff;
	cursor: pointer;
	text-decoration: underline;
}

.user-name-link:hover {
	color: #66b1ff;
}
</style>
